package railRoad.web.slaves;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import railRoad.Passenger;
import railRoad.User;
import railRoad.web.slaves.interfaces.ISlaveServlet;
import railRoad.worker.FactoryRW;

public class RegisterServlet implements ISlaveServlet {

	public void work(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		Map<?, ?> parameterMap = req.getParameterMap();
		String url = "/pages/register.jsp";

		if (parameterMap.containsKey("login")
				&& parameterMap.containsKey("name")
				&& parameterMap.containsKey("surname")
				&& parameterMap.containsKey("pass")
				&& parameterMap.containsKey("email")) {

			String login = (String) req.getParameterValues("login")[0];
			String name = (String) req.getParameterValues("name")[0];
			String surname = (String) req.getParameterValues("surname")[0];
			String pass = (String) req.getParameterValues("pass")[0];
			String email = (String) req.getParameterValues("email")[0];

			Passenger human = new Passenger(0, null, surname, name);

			req.getSession(true).setAttribute("wrongLogin", Boolean.TRUE);

			User userTst = new User();

			userTst = FactoryRW.select(userTst, login);

			if (userTst == null) {

				url = "/index.jsp";

				FactoryRW.insert(human, 0);

				User user = new User(0, login, pass, email,
						human.getPassenger_id(), false);

				FactoryRW.insert(user, 0);

				req.getSession().removeAttribute("wrongLogin");
				req.getSession().setAttribute("auth", Boolean.TRUE);
				req.getSession().setAttribute("auth", Boolean.FALSE);
				req.getSession().setAttribute("user_id", user.getUser_id());
			}// if userTst
		}// if parametrMap
		resp.sendRedirect(url);
	}// work
}// RegisterServlet
